# scheduler.py

import os
import time
import subprocess
from datetime import datetime
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# ----------------------------
# 配置部分
# ----------------------------
INPUT_DIR = "input"
SCRIPTS = [
    "qwen.py",
    "parser.py",
    "simpleinsert.py"
]


# ----------------------------
# 文件系统事件处理器
# ----------------------------
class InputFileHandler(FileSystemEventHandler):
    def on_modified(self, event):
        self.handle_event(event)

    def on_created(self, event):
        self.handle_event(event)

    def handle_event(self, event):
        if event.is_directory:
            return

        file_path = event.src_path
        filename = os.path.basename(file_path)

        if filename.endswith(".txt"):
            print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 检测到文件变更: {filename}")
            self.run_pipeline()

    def run_pipeline(self):
        """依次运行 qwen → parser → simpleinsert"""
        for script in SCRIPTS:
            try:
                print(f" 正在执行脚本: {script}")
                result = subprocess.run(["python", script], check=True)
                if result.returncode == 0:
                    print(f" 脚本 {script} 执行成功")
                else:
                    print(f"脚本 {script} 执行失败，返回码: {result.returncode}")
            except subprocess.CalledProcessError as e:
                print(f"执行脚本 {script} 出错: {e}")


# ----------------------------
# 主程序入口
# ----------------------------
def main():
    print(f"[INFO] 开始监听目录: {INPUT_DIR}")
    print(f"[INFO] 将自动触发以下流程:")
    print("       qwen.py → parser.py → simpleinsert.py")

    event_handler = InputFileHandler()
    observer = Observer()
    observer.schedule(event_handler, path=INPUT_DIR, recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        print("\n 程序已中断，停止监听...")

    observer.join()


if __name__ == "__main__":
    main()